<template>
	<view class="living">
		<!-- waiting-image="https://www.metamirror.cn:8085/profile/upload/2024/08/01/pausevideo.png" -->
		<live-pusher id='livePusher' ref="livePusher" class="livePusher" 
			:url="url"
			:mode="mode" 
			:muted="false" 
			:enable-camera="true" 
			:auto-focus="true" 
			:beauty="beauty" 
			:whiteness="whiteness"
			:aspect="aspect" 
			:remote-mirror="mirror"
			local-mirror="auto"
			@statechange="statechange" 
			@netstatus="netstatus" 
			@error = "error"
		></live-pusher>
		<view class="live-status" style="position: absolute;right: 0;
										 top: 0;">
			<view class="status-text" style="width: 440rpx;height: 40px;background-color: white;
											 margin-right: 20px;margin-top: 10px;
											 line-height: 40px;font-size: 20px;text-align: center;
											 border-radius: 20px;box-shadow: 0 0 10px 0 #aaa;">
				直播状态: <text style="font-weight: bold;">{{liveStatus}}</text>
			</view>
		</view>
		<view class="controls">
			<view class="btn controls-btn" @click="showFunction">
				操作  {{ isShow ? '×' : '+' }}
			</view>
			<view class="btn" @click="start" v-if="isShow">开始直播</view>
			<view class="btn" @click="pause" v-if="isShow">暂停直播</view>
			<view class="btn" @click="resume" v-if="isShow">恢复直播</view>
			<view class="btn" @click="stop" v-if="isShow">停止直播</view>
			<!-- <view class="btn" @click="snapshot" v-if="isShow">快照</view> -->
			<!-- <view class="btn" @click="startPreview" v-if="isShow">开启摄像头预览</view> -->
			<!-- <view class="btn" @click="stopPreview" v-if="isShow">关闭摄像头预览</view> -->
			<view class="btn" @click="switchCamera" v-if="isShow">切换摄像头</view>
		</view>
	</view>
</template>
 
<script>
import { GET_USER_INFO } from '../../../utils/CommonValues';
import request from '../../../utils/request';
    export default {
        data() {
			return {
				liveStatus: '待开播', // 直播状态
				url: "rtmp://198051.push.tlivecloud.com/live/joker?txSecret=6142fb7c19607b60365a4d3694ac8724&txTime=6657E1FF",
				mode: "FHD" ,//推流视频模式，可取值：SD（标清）, HD（高清）, FHD（超清）。
				beauty: 0, //颜，取值范围 0-9（iOS取值范围为1） ，0 表示关闭。
				whiteness: 0, //美白，取值范围 0-9（iOS取值范围为1） ，0 表示关闭。
				aspect: '3:4', //视频宽高比例
				mirror: false, // 是否镜像
				isShow: false, // 功能按钮是否显示
				membersId: '',
				isLiving: false, // 是否开启了直播
				interval: 0, // 定时器的id
			}
        },
        onLoad(option) {
			this.membersId = option.membersId;
			uni.authorize({  
			  scope: 'scope.camera', // 相机权限  
			  success() {  
			    console.log('获取相机权限成功');  
			    // 继续执行相机相关操作  
			  },  
			  fail() {  
			    console.log('获取相机权限失败');  
			    // 提示用户或执行其他操作  
			  }  
			});  
			  
			uni.authorize({  
			  scope: 'scope.record', // 录音权限  
			  success() {  
			    console.log('获取录音权限成功');  
			    // 继续执行录音相关操作  
			  },  
			  fail() {  
			    console.log('获取录音权限失败');  
			    // 提示用户或执行其他操作  
			  }  
			});
			request.GET(`/txy/get-push-address-app/${this.membersId}`, null).then(response => {
				console.log(response);
				this.url = response.data;
				// 注意：需要在onReady中 或 onLoad 延时
				this.context = uni.createLivePusherContext("livePusher", this);
				this.context.startPreview();
			})
			uni.showModal({
				title: '提示',
				content: '1. ‌涉政、涉教、‌是绝对禁止的\n' + 
					     '2. ‌发布违反宪法所确定的基本原则及违反国家法律法规的内容‌严禁\n' + 
					     '3. ‌主播在直播间不许说脏话‌\n' + 
					     '4. ‌不能侵犯他人知识产权‌\n' + 
					     '以上内容是否同意?',
				confirmText: '同意',
				cancelText: '反对',
				success: (e) => {
					if(e.confirm) {
						console.log("点击了确定")
						this.getBorderStatus();
					} else {
						console.log("点击了取消")
						uni.navigateBack();
					}
				}
			})
        },
		cameraError(e) {  
		  console.error('相机出错', e.detail);  
		},
		onUnload() {
			console.log("关闭定时器");
			clearInterval(this.interval);
			if(this.isLiving) {
				// 页面隐藏后, 需要把直播状态修改为已关闭
				GET_USER_INFO().then(res => {
					request.POST(`/system/broadcast/stop/${this.membersId}`).then(response => {
						console.log(response);
						this.isLiving = false;
					})
				})
			}
		},
        methods: {
			// 根据用户id获取直播的状态
			getBorderStatus() {
				this.interval = setInterval(() => {
					request.GET(`/system/broadcast/status/${this.membersId}`)
						   .then(response => {
							   console.log("状态", response)
							   if(response.data.broadstatus == 3 && response.data.reason) {
								   uni.showModal({
										title: "当前直播已经停止, 原因: " + 
												response.data.reason
								   })
								   // 如果已经在推流了, 要停止推流
								   clearInterval(this.interval);
								   if(this.isLiving) {
									   this.stop();
								   }
							   }
						   })
				}, 1000);
			},
			showToast(title) {
				uni.showToast({
					title: title,
					icon: 'none'
				})
			},
			// 设置功能按钮是否展示
			showFunction() {
				this.isShow = !this.isShow;
			},
			videoErrorCallback: function(e) {
				uni.showModal({
					content: e.target.errMsg,
					showCancel: false
				})
			},
            statechange(e) {
                console.log("statechange:" + JSON.stringify(e));
            },
            netstatus(e) {
                console.log("netstatus:" + JSON.stringify(e));
            },
            error(e) {
				console.log("live-pusher发生错误")
                console.log("error:" + JSON.stringify(e));
            },
            start() {
				console.log("正在启动推流")
                this.context.start({
                    success: (a) => {
						if(!this.isLiving) {
							// 开启直播之后, 需要把直播状态修改为直播中
							GET_USER_INFO().then(res => {
								request.POST(`/system/broadcast/start/${this.membersId}`).then(response => {
									console.log(response);
									if(!response.data) {
										uni.showModal({
											title: '当前时间没有您的直播'
										})
										this.stop();
										return;
									}
									this.isLiving = true;
									uni.showToast({
										title: '直播已开启',
										icon: 'none'
									})
									this.liveStatus = '直播中';
									console.log("livePusher.start:" + JSON.stringify(a));  
								})
							})
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '开启直播失败',
							icon: 'none'
						})
						this.liveStatus = '开启直播失败';
						console.log("推流失败: " + JSON.stringify(err))
					}
                });
            },
            resume: function() {
                this.context.resume({
                    success: (a) => {
                        console.log("livePusher.resume:" + JSON.stringify(a));
						uni.showToast({
							title: '恢复直播成功',
							icon: 'none'
						})
						this.liveStatus = '直播中';
                    },
					fail: (err) => {
						console.log("resume失败: " + JSON.stringify(err))
					}
                });
            },
            pause: function() {
				console.log("正在暂停推流")
                this.context.pause({
                    success: (a) => {
                        console.log("livePusher.pause:" + JSON.stringify(a));
						uni.showToast({
							title: '暂停直播成功',
							icon: 'none'
						})
						this.liveStatus = '暂停直播';
                    },
					fail: (err) => {
						console.log("暂停推流失败: " + JSON.stringify(err))
					}
                });
            },
            stop() {
				console.log("正在关闭推流")
                this.context.stop({
                    success: (a) => {
						this.showToast("直播已关闭")
                        console.log(JSON.stringify(a));
						// 关闭直播后, 需要把直播状态修改为已关闭
						if(this.isLiving) {
							GET_USER_INFO().then(res => {
								request.POST(`/system/broadcast/stop/${this.membersId}`).then(response => {
									console.log(response);
									this.isLiving = false;
									uni.showToast({
										title: '直播已关闭',
										icon: 'none'
									})
									this.liveStatus = '已关播';
								})
							})
						}
                    },
					fail: (err) => {
						console.log("关闭推流失败: " + JSON.stringify(err))
					}
                });
            },
            switchCamera: function() {
				console.log("正在翻转摄像头")
                this.context.switchCamera({
                    success: (a) => {
                        console.log("livePusher.switchCamera:" + JSON.stringify(a));
                    },
					fail: (err) => {
						console.log("翻转摄像头失败: " + JSON.stringify(err))
					}
                });
            },
            startPreview: function() {
				console.log("正在开始预览")
                this.context.startPreview({
                    success: (a) => {
                        console.log("livePusher.startPreview:" + JSON.stringify(a));
                    },
					fail: (err) => {
						console.log("开始预览失败: " + JSON.stringify(err))
					}
                });
            },
            stopPreview: function() {
				console.log("正在关闭预览")
                this.context.stopPreview({
                    success: (a) => {
                        console.log("livePusher.stopPreview:" + JSON.stringify(a));
                    },
					fail: (err) => {
						console.log("关闭预览失败: " + JSON.stringify(err))
					}
                });
            }
        }
    }
</script>
 
<style lang="less">
.living {
	position: relative;
	width: 750rpx;
	height: 100vh;
}
.livePusher {
	width: 750rpx;
	height: 100vh;
}
.controls {
	position: absolute;
	left: 0;
	top: 0;
	.btn {
		width: 120px;
		height: 40px;
		font-weight: bold;
		border-radius: 10px;
		text-align: center;
		line-height: 40px;
		margin: 10px;
		background-color: rgba(255, 255, 255, .1);
		backdrop-filter: blur(15px);
		-webkit-backdrop-filter: blur(15px);
	}
	.controls-btn {
		width: 80px;
		background-color: white;
	}
}
</style>